package com.tz.farmer.service.impl;

import cn.hutool.core.util.ArrayUtil;
import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.dubbo.common.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.smartPark.msframe.result.ResultEx;
import com.tz.farmer.enums.ErrorCodeEnum;
import com.tz.farmer.mapper.EnrollInfoMapper;
import com.tz.farmer.mapper.FarmerActivesMapper;
import com.tz.farmer.model.EnrollInfo;
import com.tz.farmer.model.FarmerActives;
import com.tz.farmer.service.WebFarmerActivesService;
import com.tz.farmer.so.FarmerActivesSo;
import com.tz.farmer.util.BeanConvertUtils;
import com.tz.farmer.util.ResultExM;
import com.tz.farmer.vo.EnrollInfoVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;


@Service
public class WebFarmerActivesServiceImpl extends ServiceImpl<FarmerActivesMapper , FarmerActives> implements WebFarmerActivesService {
    @Resource
    FarmerActivesMapper farmerActivesMapper;
    @Resource
    EnrollInfoMapper enrollInfoMapper;

    @Override
    public ResultEx getActivesListByConditions(FarmerActivesSo so) {
        if ( ObjectUtils.isEmpty(so) || so.getFlag()==null || so.getFlag() > 2 || "".equals(so.getFlag())) {
            return ResultExM.builder().makeResult(ErrorCodeEnum.ERR_COMMON_BAD_REQUEST);
        }
       /* QueryWrapper query = new QueryWrapper<FarmerActives>()
                .eq("property", so.getFlag())
                .like(StringUtils.isNotEmpty(so.getKeyword()), "title", so.getKeyword())
                .like(StringUtils.isNotEmpty(so.getKeyword()), "address", so.getKeyword())
                .last(StringUtils.isNotEmpty(so.getTimeStart()),
                        " and 1= 1 and release_time >= STR_TO_DATE( '"+so.getTimeStart()+" 00:00:00','%Y-%m-%d %H:%i:%s')  and  release_time <= STR_TO_DATE(' "+so.getTimeEnd()+ " 23:59:59','%Y-%m-%d %H:%i:%s')" );

        Integer total = farmerActivesMapper.selectCount(query);
        if(total ==  null)  total=0;
        query.last("  order by release_time DESC  limit "+ (so.getCurrentPage()-1)*so.getPageSize()+ " , " + so.getPageSize());
        List list = farmerActivesMapper.selectList(query);*/

        int total = farmerActivesMapper.countFlag(so.getFlag(), so.getKeyword(), so.getTimeStart(), so.getTimeEnd());
        int n = (so.getCurrentPage()-1)*so.getPageSize();
        int m =so.getPageSize();
        List<FarmerActives> list = farmerActivesMapper.selectConditionList(so.getFlag(), so.getKeyword(), so.getTimeStart(), so.getTimeEnd(),n,m);
        Map<String, Object> map = new Hashtable<>();
        map.put("total", total);
        map.put("data", list);
        return ResultExM.builder().makeResult(ErrorCodeEnum.ERR_COMMON_SUCCEED, map);
    }

    @Transactional
    @Override
    public ResultEx updateAndAddActives(FarmerActivesSo so) {
        if (ObjectUtils.isEmpty(so) || StringUtils.isEmpty(so.getDoFlag())) {
            return ResultExM.builder().makeResult(ErrorCodeEnum.ERR_COMMON_BAD_REQUEST);
        }
        if (so.getDoFlag().equals("1")) { //添加
            FarmerActives farmerActives = BeanConvertUtils.copyProperties(so, FarmerActives.class);
            farmerActives.setProperty(so.getFlag());
            farmerActives.setReleaseTime(LocalDateTime.now());

            boolean save = this.save(farmerActives);
            if(save){
                return ResultExM.builder().makeResult(ErrorCodeEnum.ERR_COMMON_SUCCEED);
            }
            return ResultExM.builder().makeResult(ErrorCodeEnum.ERR_COMMON_FAIL);

        } else if (so.getDoFlag().equals("2")) { //修改 置顶 下架

            if (so.getId() == null || so.getId() <= 0) {
                return ResultExM.builder().makeResult(ErrorCodeEnum.ERR_COMMON_BAD_REQUEST);
            }
            FarmerActives farmerActives = BeanConvertUtils.copyProperties(so, FarmerActives.class);
            if(so.getIsSued() != null && so.getIsSued() == 0){
                farmerActives.setReleaseTime(LocalDateTime.now());
            }
            if(so.getIsTop() != null && so.getIsTop() == 1){
                int i = farmerActivesMapper.selectMaxTop(so.getFlag());
                i=i+1;
                farmerActives.setTop(i);
            }
            boolean update = this.updateById(farmerActives);
            if (update) {
                return ResultExM.builder().makeResult(ErrorCodeEnum.ERR_COMMON_SUCCEED);
            }
            return ResultExM.builder().makeResult(ErrorCodeEnum.ERR_COMMON_UPDATE_FAIL_ERROR);
        }else if (so.getDoFlag().equals("3")) { //发布

            if (so.getId() == null || so.getId() <= 0) {
                return ResultExM.builder().makeResult(ErrorCodeEnum.ERR_COMMON_BAD_REQUEST);
            }
            FarmerActives farmerActives = farmerActivesMapper.selectOne(new QueryWrapper<FarmerActives>().eq("id", so.getId()));
            if(ObjectUtils.isEmpty(farmerActives)
                    ||"".equals(farmerActives.getAddress())
                    || farmerActives.getAddress() == null
                    ||"".equals(farmerActives.getPhone())
                    || farmerActives.getPhone() == null
                    ||"".equals(farmerActives.getJoinPeople())
                    || farmerActives.getJoinPeople() == null
                    || "".equals(farmerActives.getTitle())
                    || farmerActives.getTitle() == null
                    || "".equals(farmerActives.getActiveText())
                    || farmerActives.getActiveText() == null){
                return ResultExM.builder().makeResult(ErrorCodeEnum.ERR_COMMON_ISSUE);
            }
            FarmerActives actives = BeanConvertUtils.copyProperties(so, FarmerActives.class);
            farmerActives.setReleaseTime(LocalDateTime.now());
            boolean update = this.updateById(actives);
            if (update) {
                return ResultExM.builder().makeResult(ErrorCodeEnum.ERR_COMMON_SUCCEED);
            }
            return ResultExM.builder().makeResult(ErrorCodeEnum.ERR_COMMON_UPDATE_FAIL_ERROR);
        }else {
            return ResultExM.builder().makeResult(ErrorCodeEnum.ERR_COMMON_BAD_REQUEST);
        }
    }

    @Override
    public ResultEx getActivesApplyPeopleList(FarmerActivesSo so) {
        if(ObjectUtils.isEmpty(so)||"".equals(so.getId())){
            return  ResultExM.builder().makeResult(ErrorCodeEnum.ERR_COMMON_BAD_REQUEST);
        }

        Page<EnrollInfo> page = (Page<EnrollInfo>)enrollInfoMapper.selectPage(
                new Page<>(so.getCurrentPage(), so.getPageSize()),
                new QueryWrapper<EnrollInfo>()
                        .eq("activity_id", so.getId()).in(so.getIds() != null ,"id",so.getIds()));

        Map<String, Object> map = new Hashtable<>();
        map.put("total", page.getTotal());
       /* if (page.getTotal() == 0) {
            return ResultExM.builder().makeResult(ErrorCodeEnum.ERR_COMMON_NO_DATA);
        }*/
        map.put("data", page.getRecords());

        return  ResultExM.builder().makeResult(ErrorCodeEnum.ERR_COMMON_SUCCEED,map);
    }

    @Override
    public List<EnrollInfoVo> getApplyPeopleDownLoadList(FarmerActivesSo so) {
        List<EnrollInfoVo> listVo = new ArrayList<>();
        List<EnrollInfo> list = enrollInfoMapper.selectList(
                new QueryWrapper<EnrollInfo>().eq("activity_id", so.getId())
                        .in(ArrayUtil.isNotEmpty(so.getIds()),"id",so.getIds()));

        if(CollectionUtils.isNotEmpty(list) || list.size() > 0){
            for ( int i = 0 ; i<list.size() ; i++) {
                EnrollInfoVo enrollInfoVo = BeanConvertUtils.copyProperties(list.get(i), EnrollInfoVo.class);
                FarmerActives farmerActives = farmerActivesMapper.selectById(list.get(i).getActivityId());
                enrollInfoVo.setActivityName(farmerActives.getTitle());
                LocalDateTime createTime = list.get(i).getApplyTime();
                DateTimeFormatter sf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                enrollInfoVo.setApplyTime(sf.format(createTime));
                listVo.add(enrollInfoVo);
            }
        }
        if(CollectionUtils.isEmpty(listVo) || listVo.size() < 0){
            return new ArrayList<>();
        }
        return  listVo;
    }

    @Override
    public ResultEx getOneDetails(FarmerActivesSo so) {

        if("".equals(so.getId()) || so.getId() == null){
            return ResultExM.builder().makeResult(ErrorCodeEnum.ERR_COMMON_BAD_REQUEST);
        }
        FarmerActives farmerActives = farmerActivesMapper.selectById(so.getId());
        if(ObjectUtils.isEmpty(farmerActives)){
            return  ResultExM.builder().makeResult(ErrorCodeEnum.ERR_COMMON_NO_DATA);
        }
        return  ResultExM.builder().makeResult(ErrorCodeEnum.ERR_COMMON_SUCCEED,farmerActives);
    }

    @Override
    public ResultEx deleteOne(FarmerActivesSo so) {
        if("".equals(so.getId()) || so.getId() == null){
            return ResultExM.builder().makeResult(ErrorCodeEnum.ERR_COMMON_BAD_REQUEST);
        }
        int id = farmerActivesMapper.delete(new QueryWrapper<FarmerActives>().eq("id", so.getId()));
        if(id > 0){
            return ResultExM.builder().makeResult(ErrorCodeEnum.ERR_COMMON_SUCCEED);
        }

        return ResultExM.builder().makeResult(ErrorCodeEnum.ERR_COMMON_DELETE_FAIL_ERROR);
    }


}
